<template>
    <div class="layout-route">
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="订单号" prop="order_id">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_id" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="订单编号" prop="order_number">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_number" placeholder="请输入订单编号" clearable size="small" style="width: 240px"/>
                </el-form-item>
                <el-form-item label="店铺" prop="shop_id">
                    <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="SKU" prop="sku">
                    <el-input v-model.trim="queryParams.sku" placeholder="请输入SKU" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item> -->
                <!-- <el-form-item label="仓库:" prop="warehouse_id">
                        <el-select v-model="queryParams.warehouse_id" placeholder="请选择" clearable>
                            <el-option
                                v-for="item in overseas_warehouse_arr"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                </el-form-item> -->
                <el-form-item label="是否拆单:" prop="split_status">
                        <el-select v-model="queryParams.split_status" placeholder="全部" clearable>
                            <el-option
                                v-for="item in split_status_arr"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                </el-form-item>
                <el-form-item label="物流单号" prop="tracking_number">
                    <el-input v-model.trim="queryParams.tracking_number" placeholder="请输入物流单号" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <el-date-picker v-model="queryParams.create_time"
                        type="daterange"
                        range-separator="至"
                        @change="handleDateRangeChangec"  
                        start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="发货时间" prop="update_time">
                    <el-date-picker v-model="queryParams.update_time"
                        type="daterange"
                        range-separator="至"
                        @change="handleDateRangeChange"  
                        start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" size="large" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="large" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                        <el-select
                            v-model="overseas_warehouse"
                            clearable
                            placeholder="请选择海外仓">
                                <el-option
                                    v-for="item in overseas_warehouse_arr"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    <span style="float: left">{{ item.label }}</span>
                                </el-option>
                        </el-select>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-plus" @click="handleModification">自发货</el-button>
                </el-col>

                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download"  :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                    <el-col :span="1.5">
                        <el-upload
                            class="upload-demo"
                            ref="upload"
                            :action="api.upload"
                            :headers="headers"
                            :before-upload="handleBeforeUpload"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :show-file-list="false">
                            <el-button slot="trigger" type="success">上传文件</el-button>
                        </el-upload>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-plus" @click="MarkAsProcessed">标记成已处理</el-button>
                    </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
    <el-tabs v-model="activeTab" @tab-click="handleStatus" type="border-card">
        <el-tab-pane v-for="(item, index) in status" :key="index" :label="item.label" :name="item.value.toString()">
            <el-tabs  v-if="queryParams.ship_status == 'AutomaticShipping'" tab-position="left" v-model="activeTab2" @tab-click="handleStatus2" type="border-card">
                <el-tab-pane v-for="(item, index) in status2" :key="index" :label="item.label" :name="item.value.toString()">
                        </el-tab-pane>
            <el-table 
                v-loading="loading" 
                :data="tableData" 
                border script 
                @selection-change="handleSelectionChange"  
                ref="multipleTable"  
            >
                <el-table-column type="selection" width="55" 
                ></el-table-column>
                <el-table-column label="订单号" prop="order_id" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="订单编号" prop="order_number" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="店铺" prop="shop_name" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="SKU" prop="sku" min-width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="是否拆单" min-width="100">
                    <template slot-scope="scope">
                        <el-tag effect="dark" :type="scope.row.split_status == 1 ? 'success' : 'info'">{{scope.row.split_status == 1 ? '是' : '否'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="是否发货" min-width="100">
                    <template slot-scope="scope">
                        <el-tag effect="dark" :type="scope.row.send_status_type">{{scope.row.send_status}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" min-width="100">
                    <template slot-scope="scope">
                        <el-tag effect="dark" :type="scope.row.ship_status_type">{{scope.row.ship_status}}</el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="仓库" prop="warehouse_id" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="推荐仓库" prop="warehouse_id_plan" min-width="200" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="发货详情" prop="msg" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="物流单号" prop="tracking_number" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户昵称" prop="buyer_name" min-width="200" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="邮箱" prop="buyer_email" min-width="200" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="地址" prop="address" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                <el-table-column label="发货时间" prop="update_time" min-width="160"></el-table-column>
                <!-- <el-table-column label="操作" fixed="right" min-width="100">
                    <template slot-scope="scope">
                        <el-button el-button type="text" icon="el-icon-search" @click="showDetailDialog(scope.row, 'view')">发货日志</el-button>
                    </template>
                </el-table-column> -->
            </el-table>
            </el-tabs>

            <el-table 
                v-else
                v-loading="loading" 
                :data="tableData" 
                border script 
                @selection-change="handleSelectionChange"  
                ref="multipleTable"  
            >
                <el-table-column type="selection" width="55" 
                ></el-table-column>
                <el-table-column label="订单号" prop="order_id" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="订单编号" prop="order_number" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="店铺" prop="shop_name" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="SKU" prop="sku" min-width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="是否拆单" min-width="100">
                    <template slot-scope="scope">
                        <el-tag effect="dark" :type="scope.row.split_status == 1 ? 'success' : 'info'">{{scope.row.split_status == 1 ? '是' : '否'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="是否发货" min-width="100">
                    <template slot-scope="scope">
                    <el-tag effect="dark" :type="scope.row.send_status_type">{{scope.row.send_status}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" min-width="100">
                    <template slot-scope="scope">
                    <el-tag effect="dark" :type="scope.row.ship_status_type">{{scope.row.ship_status}}</el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="仓库" prop="warehouse_id" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="推荐仓库" prop="warehouse_id_plan" min-width="200" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="发货详情" prop="msg" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="物流单号" prop="tracking_number" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户昵称" prop="buyer_name" min-width="200" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="邮箱" prop="buyer_email" min-width="200" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="地址" prop="address" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                <el-table-column label="发货时间" prop="update_time" min-width="160"></el-table-column>
                <!-- <el-table-column label="操作" fixed="right" min-width="100">
                    <template slot-scope="scope">
                        <el-button el-button type="text" icon="el-icon-search" @click="showDetailDialog(scope.row, 'view')">发货日志</el-button>
                    </template>
                </el-table-column> -->
            </el-table>

        </el-tab-pane>
    </el-tabs>
            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList"></pagination>
        </div>
        <!-- <detail-dialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" :type="detailDialog.type" @success="handleQuery"></detail-dialog> -->
    </div>
</template>

<script>
import { queryOrderList, exportOrder } from '@/api/orderdeliver'
import { getShopList } from '@/api/shop'
import { STATUS_LIST } from './constant'
import { exportFile } from '@/utils/index'
import { getToken } from '@/utils/auth'
import DetailDialog from './components/DetailDialog.vue'
export default {
    name: 'OrderList',
    components: { DetailDialog },
    data() {
        return {
            fileList: [],
            overseas_warehouse: '3',
            split_status_arr: [
                {
                    value: '1',
                    label: '是'
                },
                {
                    value: '0',
                    label: '否'
                },

            ],
            overseas_warehouse_arr: [
                // {
                //     value: '1',
                //     label: 'JJS'
                // },
                {
                    value: '3',
                    label: '金蚁'
                },
                // {
                //     value: '4',
                //     label: '顺丰'
                // },
                // {
                //     value: '6',
                //     label: '易境通'
                // },
            ],
            api: {
                index: `/order/orderdeliver/index`,
                export: `/order/orderdeliver/export`,
                upload: process.env.VUE_APP_BASE_API + `/order/Orderdeliver/uploads`,
                automatic_shipping: `/order/orderdeliver/automatic_shipping`,
                MarkAsProcessed: `/order/orderdeliver/MarkAsProcessed`,
            },
            headers: {
                token: getToken(),
            },
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            STATUS_LIST,
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                order_id: undefined,
                order_number: undefined,
                split_status: "",
                ship_status: "",
                shop_id: undefined,
                name: undefined,
                financial_status: undefined,
                fulfillment_status: undefined,
                create_time: [],
                update_time: [],
                keyword: undefined,
            },
            detailDialog: {
                visible: false,
                data: {},
                type: ''
            },
            shopList: [],
            multipleSelection: [],

            status: [
                { label: '全部', value: '' },
                { label: '自动发货', value: 'AutomaticShipping' },
                { label: '国内仓发货', value: 'DomesticWarehouseShipment' },
                { label: '排队发货中', value: '1' },
                { label: '发货异常', value: '2' },
                { label: '回传物流单号', value: '3' },
                { label: '发货成功', value: '4' },
                { label: '已处理', value: '5' },
                { label: '发货异常标记成已处理', value: '6' },
                { label: '补发订单', value: '10' },
            ],
            activeTab: '',
            activeTab2: '',
            status2: [
                { label: '推荐仓库', value: '' },
                // { label: 'JJS', value: '1' },
                { label: '金蚁', value: '3' },
                // { label: '顺丰', value: '4' },
            ],
        }
    },
    async created() {
        this.loading = true
        try {
            const result = await getShopList()
            this.shopList = result?.data?.list ?? []
        } catch (error) {
            console.log(error)
            this.loading = false
        }
        this.getList()
    },
    methods: {
        MarkAsProcessed(row) {
            if(this.multipleSelection == ''){
                return this.msgError('请勾选再操作')
            }
            this.$confirm(`是否确认修改为已处理?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.loading = true
                    this.MarkAsProcesseds()
                })
                .catch(() => {})
        },

        async MarkAsProcesseds() {
            let response = await this.request.post(this.api.MarkAsProcessed, { 
                    ids:this.multipleSelection 
                }
            )
            this.getList()
            this.msgSuccess('操作成功')
            this.loading = false
        },

        handleDateRangeChangec(value) {  
            this.queryParams.create_time = value.map(dateStr => {  
                const date = new Date(dateStr);  
                const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;  
                return formattedDate;  
            });  
        },
        handleDateRangeChange(value) {  
            this.queryParams.update_time = value.map(dateStr => {  
                const date = new Date(dateStr);  
                const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;  
                return formattedDate;  
            });  
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            exportOrder(qyparams)
                .then(res => {
                    console.log(res)
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        showDetailDialog(row, type) {
            this.detailDialog.visible = true
            this.detailDialog.data = row
            this.detailDialog.type = type
        },
        //列表
        getList() {
            this.multipleSelection = [];
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            // 自发货 需要该字段
            if(qyparams.ship_status !== 'AutomaticShipping') {
                qyparams.warehouse_id_plan = ''
            }
            queryOrderList(qyparams)
                .then(response => {
                    this.tableData = response.data.list 
                    this.total = response.data.total 
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },

        
        handleModification(row) {
            if(this.multipleSelection == ''){
                return this.msgError('请勾选再操作')
            }
            if(this.overseas_warehouse == ''){
                return this.msgError('请选择仓库再操作')
            }
            this.$confirm(`是否确认自动发货，过程大概需要一分钟?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.loading = true
                    this.automatic_shippings()
                })
                .catch(() => {})
        },

        async automatic_shippings() {
            let response = await this.request.post(this.api.automatic_shipping, { 
                    ids:this.multipleSelection ,
                    warehouse_id:this.overseas_warehouse,
                }
            )
            console.log('response',response);
            this.getList()
            this.msgSuccess('操作成功，请在发货日志中查看明细')
            this.loading = false
        },

        // 案列：当前组件格式化方法
        testFormatter(prop) {
            return prop
        },

        handleBeforeUpload() {
            this.loading = true
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        
        // 上传成功回调
        handleUploadSuccess(res) {
            this.loading = false
            if (res.code == 200) {
                this.$message.success(res.msg)
            } else {
                this.$message.error(res.msg)
            }
            this.getList();
        },
        // 上传失败
        handleUploadError() {
            this.$message.error('上传失败')
            this.getList();
        },
        handleSelectionChange(val) {  
            this.multipleSelection = val.map(item => item.id)
            console.log('test',this.multipleSelection);
        }, 
        
        handleStatus(tab) {
            this.queryParams.ship_status = tab.name
            this.getList()
        },
        handleStatus2(tab) {
            this.overseas_warehouse = tab.name
            this.queryParams.warehouse_id_plan = tab.name
            this.getList()
        },
    },
}
</script>
